package com.game.common.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class SmsUtils {

    /**
     * 短信模板签名
     */
    @Value("${utils.sms.signature}")
    private String signature;

    @Value("${utils.sms.project}")
    private String project;

    /**
     * 短信登录路径
     */
    @Value("${utils.sms.url}")
    private String smsUrl;

    @Value("${utils.sms.xurl}")
    private String smsXUrl;

    @Value("${utils.sms.appId}")
    private String appId;

    @Value("${utils.sms.appKey}")
    private String appKey;

    /**
     * 短信发送
     * @param phoneNumber
     */
    public Boolean sendSms(String phoneNumber,String code){
        SmsDto smsDto = new SmsDto();
        smsDto.setTo(phoneNumber)
                .setAppid(appId)
                .setSignature(appKey);  // 使用配置的signature而不是appKey
        String oldContent = smsDto.getContent();
        String content = oldContent.replace("${signature}", signature)
                .replace("${smsCode}", code)
                .replace("${minute}", "5");
        smsDto.setContent(content);
        String requestBody = JSONObject.from(smsDto).toString();
        String result = HttpUtil.post(smsUrl, requestBody);
        JSONObject responseBody = JSONObject.parseObject(result);
        String status = responseBody.getString("status");
        if (status.equals("success")){
            return true;
        }else {
            System.err.println("短信发送失败: " + responseBody.getString("msg")); // 添加错误日志
            return false;
        }
    }

    /**
     * 模板发送
     * @param phoneNumber
     */
    public Boolean sendXSms(String phoneNumber,String code){
        SmsDto smsDto = new SmsDto();
        smsDto.setTo(phoneNumber)
                .setAppid(appId)
                .setProject(project)
                .setSignature(appKey);
        String vars = "{\"code\":\""+code+"\"}";
        smsDto.setVars(vars);
        String requestBody = JSONObject.from(smsDto).toString();
        String result = HttpUtil.post(smsXUrl, requestBody);
        JSONObject responseBody = JSONObject.parseObject(result);
        String status = responseBody.getString("status");
        if (status.equals("success")){
            return true;
        }else {
            System.err.println("短信发送失败: " + responseBody.getString("msg")); // 添加错误日志
            return false;
        }
    }




}
